<!--
author:        hejiyang <silentmanager@163.com>
date:          2024-12-16 09:56:36
component:     updateBlacklist
Copyright © YourCompanyName All rights reserved
添加/移除黑名单
-->

<template>
  <el-dialog
    :destroy-on-close="true"
    :title="props.blackStatus ? '添加黑名单' : '移除黑名单'"
    v-model="isVisible"
    @close="handleClose"
    width="600px"
  >
    <el-form
      ref="formRef"
      style="max-width: 600px"
      :model="formData"
      :rules="rules"
      label-width="auto"
      status-icon
    >
      <el-form-item label="客户手机号" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入手机号" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button type="primary" :loading="loading" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { editBlacklistStatus } from '@/api/customer'
import { FormInstance, FormRules } from 'element-plus'
import { ref, watch, defineProps, defineEmits } from 'vue'
const message = useMessage()
// 定义组件的 props
interface Props {
  visible: boolean
  blackStatus: boolean
}

const formRef = ref<FormInstance>()
const formData = reactive({
  mobile: ''
})

const rules = reactive<FormRules<{ mobile: string }>>({
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^[1][3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ]
})

// 获取 props 和 emits
const props = defineProps<Props>()
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void // 添加 success 事件
}>()

// 局部状态变量，用于管理弹窗的可见性
const isVisible = ref<boolean>(props.visible)
const loading = ref(false)

// 关闭弹窗的处理函数
const handleClose = () => {
  isVisible.value = false // 设置局部状态
  emit('update:visible', false) // 通知父组件
  formData.mobile = ''
}

// 保存备注的处理函数
const handleSave = async () => {
  loading.value = true
  try {
    await formRef.value?.validate()
    const res = await editBlacklistStatus(formData.mobile, props.blackStatus)
    if (res.code === 0) {
      if (props.blackStatus) {
        message.success('添加成功')
      } else {
        message.success('移除成功')
      }
    }
    await emit('success') // 通知父组件
    handleClose() // 保存后关闭弹窗
    loading.value = false
  } catch (e) {
    loading.value = false
    console.error(e)
  }
}

// 监视 props.visible 的变化，以更新局部状态
watch(
  () => props.visible,
  (newValue) => {
    isVisible.value = newValue
  }
)
</script>

<style scoped>
/* 您的样式 */
</style>
